package com.neouton.crm.pm.service.impl;

import cn.hutool.json.JSONObject;
import com.alibaba.fastjson.JSONArray;
import com.neouton.common.entity.FeeMainVO;
import com.neouton.common.util.AuthUtils;
import com.neouton.common.util.Constants;
import com.neouton.common.util.ResponseAPI;
import com.neouton.crm.approval.entity.ApprovalVO;
import com.neouton.crm.cm.service.impl.CostMigrateServiceImpl;
import com.neouton.crm.dictionary.mapper.DictionaryMapper;
import com.neouton.crm.dictionary.service.IDictionaryService;
import com.neouton.crm.entity.SysDeptVO;
import com.neouton.crm.entity.SysUserEntity;
import com.neouton.crm.op.service.impl.SalesOpportunityServiceImpl;
import com.neouton.crm.payRecords.entity.PaymentRecords;
import com.neouton.crm.payRecords.entity.PaymentRequest;
import com.neouton.crm.payRecords.mapper.PaymentRecordsMapper;
import com.neouton.crm.payRecords.mapper.PaymentRequestMapper;
import com.neouton.crm.pm.entity.*;
import com.neouton.crm.pm.mapper.BrAndBmrMapper;
import com.neouton.crm.pm.mapper.ContractInfoMapper;
import com.neouton.crm.pm.mapper.ProjectMemberMapper;
import com.neouton.crm.pm.mapper.PurchaseOrdeMapper;
import com.neouton.crm.pm.service.ProjectMemberService;
import com.neouton.crm.receiptRecords.entity.ReceiptRecords;
import com.neouton.crm.receiptRecords.mapper.ReceiptRecordsMapper;
import com.neouton.crm.sales.entity.SalesAuditVO;
import com.neouton.crm.sales.mapper.SalesAuditBackMapper;
import com.neouton.crm.sales.mapper.SalesAuditMapper;
import com.neouton.feginClient.FeginService;
import com.neouton.feginClient.ReimburseService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;

/**
 * @author TheSail
 * @date 2022/11/09 18:25:03
 * @description
 */
@Service
public class ProjectMemberServiceImpl implements ProjectMemberService {
    @Resource
    private ProjectMemberMapper projectMemberMapper;
    @Resource
    private DictionaryMapper dictionaryMapper;
    @Resource
    private FeginService feginService;
    @Resource
    private SalesAuditMapper auditMapper;
    @Resource
    private ContractInfoMapper contractInfoMapper;
    @Resource
    private PurchaseOrdeMapper purchaseOrdeMapper;
    @Resource
    private BrAndBmrMapper brAndBmrMapper;
    @Resource
    private ReceiptRecordsMapper receiptRecordsMapper;
    @Resource
    private PaymentRecordsMapper recordsMapper;
    @Resource
    private PaymentRequestMapper requestMapper;
    @Resource
    private IDictionaryService dictionaryService;
    @Resource
    private ReimburseService reimburseService;

    /**
     * 权限判断
     *
     * @param userId
     * @return 0查所有，1查本部门，2查自己,3项目成员
     */
    @Override
    public int queryAuth(Integer userId, String type) {
        List<SysUserEntity> userIds = dictionaryMapper.queryMenuUserIdsByCode(type);
        for (SysUserEntity user : userIds) {
            if (user.getUserId().equals(userId)) {
                return 0;
            }
        }
//        ProjectMemberVO user = projectMemberMapper.queryUser(userId);
//        if (user.getIsLeader() == 1) {
//            return 1;
//        }
        return 2;
    }

    @Override
    public List<SysUserEntity> queryUserProjectList(Integer userId, String token) {
        List<SysUserEntity> userList = new ArrayList<>();
        SysUserEntity user = feginService.searchUserInfoByIds(userId, token).getResult();
        if (user.getIsLeader() == 1) {
            userList = feginService.getUserIgnoreFlag(token).getResult();
        }
        userList.add(user);
        return userList;
    }

    @Override
    public List<SysUserEntity> queryUserList(Integer userId, String authCode, String token) {
        List<SysUserEntity> userList = new ArrayList<>();
        List<SysUserEntity> authUserIList = dictionaryService.queryAuthUserIdsByCode(authCode);
        boolean result = false;
        for (SysUserEntity user : authUserIList) {
            if (Objects.equals(user.getUserId(), userId)) {
                result = true;
            }
        }
        if (result) {
            userList = feginService.getUserIgnoreFlag(token).getResult();
        } else {
            SysUserEntity user = feginService.searchUserInfoByIds(userId, token).getResult();
            if (user.getIsLeader() == 1) {
                userList = feginService.recursiveQueryAllUserByLeaderId(userId, token).getResult();
            }
            userList.add(user);
        }
        //股东会查所有
//        List<SysDeptVO> userDepts = user.getUserDepts();
//        for (SysDeptVO item : userDepts) {
//            if (item.getDeptId() == 1) {
//                return feginService.getUserIgnoreFlag(token).getResult();
//            }
//        }
        return userList;
    }

    /**
     * 终验验证 true则通过继续，false则结束返回
     *
     * @param projectManageVO
     * @param token
     * @return
     */
    public boolean testFinalReview(SalesProjectManageVO projectManageVO, String token) {
        boolean result = true;
        //费用迁移
        List<SalesAuditVO> auditVOS = auditMapper.queryOpInfoByPM(projectManageVO.getProjectManageId());
        if (auditVOS != null && !auditVOS.isEmpty()) {
            for (SalesAuditVO audit : auditVOS) {
                if (audit.getAuditState() == 0 || audit.getAuditState() == 5) {
                    result = false;
                }
            }
        }
        //合同订单
        List<ContractInfoVO> contractInfoVOS = contractInfoMapper.queryContractInfoByProjectId(projectManageVO.getProjectManageId(), null);
        if (contractInfoVOS != null && !contractInfoVOS.isEmpty()) {
            for (ContractInfoVO contract : contractInfoVOS) {
                if (contract.getApproval().getApprovalStatus() == 0 || contract.getApproval().getApprovalStatus() == 5) {
                    result = false;
                }
            }
        }
        //采购订单
        List<PurchaseOrderVO> purchaseOrderVOS = purchaseOrdeMapper.queryPurchaseOrdersByProjectId(projectManageVO.getProjectManageId());
        if (purchaseOrderVOS != null && !purchaseOrderVOS.isEmpty()) {
            for (PurchaseOrderVO purchase : purchaseOrderVOS) {
                if (purchase.getApproval().getApprovalStatus() == 0 || purchase.getApproval().getApprovalStatus() == 5) {
                    result = false;
                }
            }
        }
        //回款记录
        List<BackMoneyRecordVo> backMoneyRecordVos = brAndBmrMapper.queryBackMoneyRecordByProjectId(projectManageVO.getProjectManageId());
        if (backMoneyRecordVos != null && !backMoneyRecordVos.isEmpty()) {
            for (BackMoneyRecordVo bmr : backMoneyRecordVos) {
                if (bmr.getApprovalStatus() == 0 || bmr.getApprovalStatus() == 5) {
                    result = false;
                }
            }
        }
        //0开票申请|1开票记录
        List<BillingRecordVo> billingRecordVos = brAndBmrMapper.queryBillingRecordByProjectId(projectManageVO.getProjectManageId());
        if (billingRecordVos != null && !billingRecordVos.isEmpty()) {
            for (BillingRecordVo br : billingRecordVos) {
                if (br.getApprovalStatus() == 0 || br.getApprovalStatus() == 5) {
                    result = false;
                }
            }
        }
        //收票记录
        List<ReceiptRecords> receiptRecords = receiptRecordsMapper.queryReceiptRecordsByProjectId(projectManageVO.getProjectManageId());
        if (receiptRecords != null && !receiptRecords.isEmpty()) {
            for (ReceiptRecords rr : receiptRecords) {
                if (rr.getApproval().getApprovalStatus() == 0 || rr.getApproval().getApprovalStatus() == 5) {
                    result = false;
                }
            }
        }
        //付款记录
        List<PaymentRecords> paymentRecords = recordsMapper.queryPaymentRecordsByProjectId(projectManageVO.getProjectManageId());
        if (paymentRecords != null && !paymentRecords.isEmpty()) {
            for (PaymentRecords pr : paymentRecords) {
                if (pr.getApproval().getApprovalStatus() == 0 || pr.getApproval().getApprovalStatus() == 5) {
                    result = false;
                }
            }
        }
        //付款申请
        List<PaymentRequest> paymentRequests = requestMapper.queryPaymentRequestByProjectId(projectManageVO.getProjectManageId());
        if (paymentRequests != null && !paymentRequests.isEmpty()) {
            for (PaymentRequest pr : paymentRequests) {
                if (pr.getApproval().getApprovalStatus() == 0 || pr.getApproval().getApprovalStatus() == 5) {
                    result = false;
                }
            }
        }
        //退款记录      暂无审批
//        //报销单
//        FeeMainVO feeMainVO = new FeeMainVO();
//        feeMainVO.setProjectId(projectManageVO.getProjectManageId());
//        ResponseAPI responseAPI = reimburseService.queryReimburseList(feeMainVO, token);
//        String listTxt = JSONArray.toJSONString(responseAPI.getResult());
//        List<FeeMainVO> feeMains = JSONArray.parseArray(listTxt, FeeMainVO.class);
////        List<HashMap<Objects,Objects>>  obj = (ArrayList)reimburseService.queryReimburseList(feeMainVO, token).getResult();
//        if (feeMains != null && feeMains.size() > 0) {
//            for (FeeMainVO fm : feeMains) {
//                if (fm.getState() == 2) {
//                    result = false;
//                }
//            }
//        }
        return result;
    }



    public Boolean deleteProjectByOppId(Integer oppId){
        return projectMemberMapper.deleteProjectByOppId(oppId);
    }

}
